<?php
/**
* SocialEngine
*
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
* @license    http://www.modules2buy.com/license/
* @version    $Id: IndexController.php 6898 2010 YouNet $
* @author     To Anh
*/
class Flashgame_PaypalController extends Core_Controller_Action_Standard
{
    private $VARS;
    private $button;
    private $logFile;
    private $isTest=false;
    private $paymentType = 'paypal';
    public function getPackageNavigation($active = false)
    {
        $navigation = $this->_navigation = new Zend_Navigation();
        if( Engine_Api::_()->user()->getViewer()->getIdentity() )
        {  
            /*
            $navigation->addPage(array(
            'label' => Zend_Registry::get('Zend_Translate')->_('Payment History'),
            'route' => 'flashgame_paymenthistory',
            'module' => 'flashgame',
            'controller' => 'package',
            'action' => 'paymenthistory',
            'active' => $active
            ));
            */
            $navigation->addPage(array(
            'label' => Zend_Registry::get('Zend_Translate')->_('My Packages'),
            'route' => 'flashgame_userpackages',
            'module' => 'flashgame',
            'controller' => 'package',
            'action' => 'userpackages'
            ));
            $navigation->addPage(array(
            'label' => Zend_Registry::get('Zend_Translate')->_('Upgrade Packages'),
            'route' => 'flashgame_upgrade',
            'module' => 'flashgame',
            'controller' => 'package',
            'action' => 'upgrade',
            'active' => $active 
            ));
            $navigation->addPage(array(
            'label' => Zend_Registry::get('Zend_Translate')->_('Check Out'),
            'route' => 'flashgame_payment',
            'module' => 'flashgame',
            'controller' => 'paypal',
            'action' => 'payment'
            ));          
        }
        return $this->_navigation;
    } 
    public function paymentAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        if( !$this->_helper->requireUser()->isValid() ) return;
        $this->view->navigation = $this->getPackageNavigation();
        if($this->getRequest()->isPost() )
        {
            $values = $this->getRequest()->getPost();
            $this->view->package = $packages = Engine_Api::_()->flashgame()->getPackage($values['signup_package']);
            $this->view->periodtypes = Engine_Api::_()->flashgame()->getPeriodtypes(); 
            //$this->view->navigation = Engine_Api::_()->flashgame()->getPackageNavigation();
            //print $this->view->baseUrl();
            $this->requestpaypal($packages);
        }
        else
            return $this->_redirect("games/upgrade");
    } 
    public function paymenthistoryAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        if( !$this->_helper->requireUser()->isValid() ) return;
        $this->view->packages = $packages = Engine_Api::_()->flashgame()->getEnablePackages();
        $this->view->periodtypes = Engine_Api::_()->flashgame()->getPeriodtypes(); 
        //$this->view->navigation = Engine_Api::_()->flashgame()->getPackageNavigation();
    }
    public function requestAction()
    {
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction();
        try
        {          
            // insert client
            $clientTable = Engine_Api::_()->getDbtable('clients', 'flashgame');
            $client = $clientTable->createRow();
            $client->client_user_id = $this->_getParam("user_id");
            $client->save();

            // insert payment info
            $hpaymentTable = Engine_Api::_()->getDbtable('userpaymenthistory', 'flashgame');
            $hpayment = $hpaymentTable->createRow();
            $hpayment->userpaymenthistory_client_id = $client->clients_id;
            $hpayment->userpaymenthistory_date  = date('Y-m-d H:i:s');
            $hpayment->userpaymenthistory_type  = $this->paymentType;
            $hpayment->userpaymenthistory_user_id = $this->_getParam("user_id");
            $hpayment->userpaymenthistory_package = $this->_getParam("package_id");        
            $hpayment->save();

            // Commit
            $db->commit();

            // Redirect
            return $this->_redirect("games/browse");
        }
        catch( Exception $e )
        {
            $db->rollBack();
            throw $e;
        }
    }  

    public function getAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);

        if(!empty($_POST))
        {   

            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            $get_payment = $_POST;
            try
            { 
                // get package 
                $packageTable = Engine_Api::_()->getDbtable('packages', 'flashgame');
                $pselect = $packageTable->select()->where('package_id = ?', $this->_getParam("package_id"));
                $package = $packageTable->fetchRow($pselect);            
                if (count($packageTable->fetchAll($pselect)) > 0 && $package->package_price == $get_payment['payment_gross'])
                {
                    // Insert to client
                    $clientTable = Engine_Api::_()->getDbtable('clients', 'flashgame');
                    $client = $clientTable->createRow();
                    $client->client_user_id = $this->_getParam("user_id");
                    $client->client_firstname = $get_payment['first_name'];
                    $client->client_lastname = $get_payment['last_name'];
                    $client->client_email = $get_payment['payer_email'];
                    $client->client_street = utf8_decode($get_payment['address_street']);
                    $client->client_city = $get_payment['address_city'];
                    $client->client_state = $get_payment['address_state'];
                    $client->client_zipcode = $get_payment['address_zip'];
                    $client->client_country = $get_payment['address_country'];
                    //$client->client_date = date('Y-m-d H:i:s',mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    $client->save();


                    if ($get_payment['payment_status'] == 'Completed')
                    {

                        // update user membershift
                        /*
                        $uuTable = Engine_Api::_()->getDbtable('users', 'user');
                        $uselect = $uuTable->select()    
                        ->where('user_id = ?', $this->_getParam("user_id"));
                        if (count($uuTable->fetchAll($uselect)) > 0)                                
                        {
                        $userUpgrate = $uuTable->fetchRow($uselect);
                        $userUpgrate->level_id = $package->package_level_id;
                        $userUpgrate->save();
                        }
                        */
                        // insert user package 
                        $upackageTable = Engine_Api::_()->getDbtable('userpackages', 'flashgame');
                        $select = $upackageTable->select()    
                        ->where('userpackage_user_id = ?', $this->_getParam("user_id"))
                        ->where('userpackage_package_id = ?', $this->_getParam("package_id"));
                        $upackage = $upackageTable->fetchRow($select);
                        // if user didnt upgrade this package
                        // insert new package
                        // plus date
                        switch ($package->package_periodtype) 
                        {
                            case '1':
                                $dayPlus = $package->package_period;
                                break;
                            case '2':
                                $dayPlus = $package->package_period*7;
                                break;
                            case '3':
                                $dayPlus = $package->package_period*30;
                                break;
                            case '4':
                                $dayPlus = $package->package_period*365;
                        }
                        // get max expiredate of this user    
                        $maxExpiredate = Engine_Api::_()->getApi('core', 'flashgame')->getMaxExpiredate($this->_getParam("user_id"));    
                        //if (count($upackage) < 1)
                        //{
                        // add user for this package
                        $package->package_sold = $package->package_sold + 1;
                        $package->save();

                        $upackage = $upackageTable->createRow();
                        $upackage->userpackage_package_id = $this->_getParam("package_id");
                        $upackage->userpackage_user_id = $this->_getParam("user_id");

                        $upackage->userpackage_startdate = date('Y-m-d',$maxExpiredate);
                        $upackage->userpackage_expiredate = date('Y-m-d',$maxExpiredate + $dayPlus*86400);

                        // package information
                        $upackage->userpackage_name = $package->package_name; 
                        $upackage->userpackage_price = $package->package_price;  
                        $upackage->userpackage_period = $package->package_period;  
                        $upackage->userpackage_periodtype = $package->package_periodtype;                      

                        //}
                        //else
                        //{
                        // if this user upgraded this package
                        //$upackage->userpackage_expiredate = date('Y-m-d H:i:s', $maxExpiredate + $dayPlus*86400);
                        //}

                        $upackage->save();
                    }
                    // update payment history
                    // insert payment info
                    $hpaymentTable = Engine_Api::_()->getDbtable('userpaymenthistory', 'flashgame');
                    $hselect = $hpaymentTable->select()    
                    ->where('userpaymenthistory_txnid = ?', $get_payment['txn_id']);

                    if (count($hpaymentTable->fetchAll($hselect)) < 1)
                    {
                        $hpayment = $hpaymentTable->createRow();
                        $hpayment->userpaymenthistory_client_id = $client->clients_id;
                        $hpayment->userpaymenthistory_date  = date('Y-m-d H:i:s');
                        $hpayment->userpaymenthistory_type  = $this->paymentType;
                        $hpayment->userpaymenthistory_user_id = $this->_getParam("user_id");
                        $hpayment->userpaymenthistory_package = $this->_getParam("package_id");  
                        $hpayment->userpaymenthistory_txnid = $get_payment['txn_id'];     
                        $hpayment->userpaymenthistory_amount  = $package->package_price; 
                        $hpayment->save();
                    }

                    // insert paymentinfo
                    $ipaymentTable = Engine_Api::_()->getDbtable('paymentinfo', 'flashgame');
                    $iselect = $ipaymentTable->select()    
                    ->where('txnid = ?', $get_payment['txn_id']);
                    if (count($ipaymentTable->fetchAll($iselect)) < 1)
                    {
                        $ipayment = $ipaymentTable->createRow();
                        $ipayment->txnid =  $get_payment['txn_id'];
                        $ipayment->firstname = $get_payment['first_name'];
                        $ipayment->lastname = $get_payment['last_name'];
                        $ipayment->buyer_email = $get_payment['payer_email'];
                        $ipayment->street = $get_payment['address_street'];

                        $ipayment->city = $get_payment['address_city'];
                        $ipayment->state = $get_payment['address_state'];
                        $ipayment->zipcode = $get_payment['address_zip'];
                        $ipayment->quantity = $get_payment['quantity'];
                        $ipayment->paymenttype = $this->paymentType;
                        $ipayment->mc_fee = $get_payment['payment_gross'];


                        $ipayment->paymentstatus = $get_payment['payment_status'];
                        //$ipayment->pendingreason = $get_payment['mc_fee'];
                        $ipayment->txntype = $get_payment['txn_type'];
                        $ipayment->tax = $get_payment['tax'];
                        $ipayment->mc_currency = $get_payment['mc_currency'];
                        //$ipayment->reasoncode = $get_payment['mc_fee'];
                        $ipayment->custom = $get_payment['custom'];

                        $ipayment->country = $get_payment['address_country'];
                        $ipayment->datecreation = $get_payment['payment_date'];
                        $ipayment->status = $get_payment['payment_status'];
                        $ipayment->datecreation = date('Y-m-d H:i:s');
                        $ipayment->save();
                    }
                    // Commit
                    $db->commit();
                }        
                // Redirect

            }
            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
        }
        //return $this->_redirect("games/browse");
    }

    public function requestpaypal($paramaters = array())
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $table  = Engine_Api::_()->getDbTable('paymentgateways', 'flashgame');
        $select = $table->select()
        ->where('paymentgateway_typename = ?', 'paypal')
        ->where('paymentgateway_enabled = ?', '1');
        $row = $table->fetchRow($select);
		if ($row)
		{
	        $this->useSandBox(($row['paymentgateway_sandbox']=='1')?true:false);
	
	        $this->addVar('business',$row['paymentgateway_business']);    /* Payment Email */
	        $this->addVar('cmd','_xclick');
	        $this->addVar('amount',$paramaters['package_price']);
	
	        $this->addVar('item_name',$paramaters['package_name']);
	        $this->addVar('item_number',$paramaters['package_id']);
	        $this->addVar('charset','UTF-8');
	        $this->addVar('quantity','1');
	        //$buyNow->addVar('tax','1.99');
	        //$buyNow->addVar('shipping','8.00');
	        $this->addVar('currency_code','USD');
	        $this->addVar('no_shipping','0');        
	        $this->addVar('rm','2');   
	        //get current url
	        $currentUrl = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'] : "http://".$_SERVER['SERVER_NAME'];
	
	        $currentUrl .= ($_SERVER["SERVER_PORT"] != "80") ? 
	        $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$this->view->baseUrl():$this->view->baseUrl();         
	        $this->addVar('notify_url',$currentUrl . '/games/payment/get/' . $paramaters['package_id'] . '/' . $viewer->getIdentity());    
	        /*
	        Thank you Page (if any) - not included in this package*/
	
	        $this->addVar('return', $currentUrl . '/games/browse'); 
	        /*
	        Now add a button
	        */
	        $this->addButton(1);    /* Default buy now button */
	        /* or use custom buttons */
	        /*
	        $buyNow->addButton(6,'http://farm1.static.flickr.com/34/110260847_779dd141a6.jpg?v=0');
	        */
	        /* Show final form */
	        $this->showForm();
		}
		else 
		return;
    }


    /* Print Form as Link */
    public function getLink()
    {
        $url = $this->getPaypal();
        $link = 'https://'.$url.'/cgi-bin/webscr?';
        foreach($this->VARS as $item => $sub){
            $link .= $sub[0].'='.$sub[1].'&';
        }
        return $link;
    }

    /* Print Form */
    public function showForm()
    {
        $url = $this->getPaypal();
        $FORM  = '<form action="https://'.$url.'/cgi-bin/webscr" method="post"  style="display:inline;">'."\n";

        foreach($this->VARS as $item => $sub){
            $FORM .= '<input type="hidden" name="'.$sub[0].'" value="'.$sub[1].'">'."\n";
        }

        $FORM .= $this->button;    
        $FORM .= '</form>';
        echo $FORM;
    }

    /* Add variable to form */
    public function addVar($varName,$value)
    {
        $this->VARS[$varName][0] = $varName;
        $this->VARS[$varName][1] = $value;
    }

    /* Add button Image */
    public function addButton($type,$image = NULL)
    {
        switch($type)
        {
            /* Buy now */
            case 1:
                $this->button = '<input type="image" height="21" style="width:86;border:0px;"';
                $this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_paynow_SM.gif" border="0" name="submit" ';
                $this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
                break;
                /* Add to cart */    
            case 2:
                $this->button = '<input type="image" height="26" style="width:120;border:0px;"';
                $this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit"';
                $this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
                break;
                /* Donate */    
            case 3:
                $this->button = '<input type="image" height="47" style="width:122;border:0px;"';
                $this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit"';
                $this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
                break;
                /* Gift Certificate */
            case 4:    
                $this->button = '<input type="image" height="47" style="width:179;border:0px;"';
                $this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_giftCC_LG.gif" border="0" name="submit"';
                $this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
                break;
                /* Subscribe */
            case 5:    
                $this->button = '<input type="image" height="47" style="width:122;border:0px;"';
                $this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit"';
                $this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
                break;
                /* Custom Button */
            default:
                $this->button = '<input type="image" src="'.$image.'" border="0" name="submit"';
                $this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
        }
        $this->button .= "\n";
    }

    /* Helper function to actually write to logfile */
    private function doLog($_POST)
    {
        ob_start();
        echo '<pre>'; print_r($_POST); echo '</pre>';
        $logInfo = ob_get_contents();
        ob_end_clean();

        $file = fopen($this->logFile,'a');
        fwrite($file,$logInfo);
        fclose($file);
    }

    /* Check payment */
    public function checkPayment($_POST)
    {
        /* read the post from PayPal system and add 'cmd' */
        $req = 'cmd=_notify-validate';

        /* Get post values and store them in req */
        foreach ($_POST as $key => $value) {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        $url = $this->getPaypal();

        /* post back to PayPal system to validate */
        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
        $fp = fsockopen ('ssl://'.$url, 443, $errno, $errstr, 30);

        /*
        If ssl access gives you problem. try regular port:
        $fp = fsockopen ($url, 80, $errno, $errstr, 30);
        */

        if (!$fp) {
            /* HTTP ERROR */
            return false;
        } else {
            fputs ($fp, $header . $req);
            while (!feof($fp)) {
                $res = fgets ($fp, 1024);
                if (strcmp ($res, "VERIFIED") == 0) {
                    /*
                    check the payment_status is Completed
                    check that txn_id has not been previously processed
                    check that receiver_email is your Primary PayPal email
                    check that payment_amount/payment_currency are correct
                    process payment
                    */                    
                    return true;
                } else {
                    //                if (strcmp ($res, "INVALID") == 0) {
                    /*
                    log for manual investigation
                    */
                    if($this->logFile != NULL){
                        $this->doLog($_POST);
                    }
                    return false;
                }
            }
            fclose ($fp);
        }
        return false;
    }

    /* Set Test */
    public function useSandBox($value)
    {
        $this->isTest=$value;
    }

    /* Private function to get paypal url */
    private function getPaypal()
    {
        if($this->isTest == true){
            return 'www.sandbox.paypal.com';
        } else {
            return 'www.paypal.com';
        }
    }

}

